package com.what21.netfwd;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ForwardMapping {

	private InputStream input;

	private Map<AddressInfo, AddressInfo> map;

	public ForwardMapping(InputStream input) {
		this.input = input;
		this.map = parseMapping();
	}

	public ForwardMapping(String name) {
		this.input = ForwardMapping.class.getResourceAsStream(name);
		this.map = parseMapping();
	}

	public ForwardMapping(File file) {
		try {
			this.input = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		this.map = parseMapping();
	}

	public Map<AddressInfo, AddressInfo> toMapping() {
		return this.map;
	}

	public Map<AddressInfo, AddressInfo> parseMapping() {
		Map<AddressInfo, AddressInfo> mappings = new HashMap<AddressInfo, AddressInfo>();
		Properties props = new Properties();
		try {
			props.load(this.input);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Set<?> keySet = props.keySet();
		for (Object key : keySet) {
			String strKey = (String) key;
			String value = props.getProperty(strKey);
			if (strKey.contains(":") && value.contains(":")) {
				try {
					String[] srcInfo = strKey.split(":");
					String[] descInfo = value.split(":");
					String srcIP = srcInfo[0].trim();
					String descIP = descInfo[0].trim();
					int srcPort = Integer.parseInt(srcInfo[1].trim());
					int descPort = Integer.parseInt(descInfo[1].trim());
					AddressInfo keyAddress = new AddressInfo(srcIP, srcPort);
					AddressInfo valueAddress = new AddressInfo(descIP, descPort);
					ForwardUtil.debug("source > " + keyAddress + ", target > " + valueAddress);
					mappings.put(keyAddress, valueAddress);
				} catch (Exception e) {
				}
			}
		}
		return mappings;
	}
}
